import { defineStore } from 'pinia'
import type { NewsArticle, Category, SearchParams } from '@/types'
import { 
  mockArticles, 
  mockCategories, 
  getHotArticles, 
  getLatestArticles,
  getArticlesByCategory,
  searchArticles,
  getArticleById,
  getRecommendedArticles
} from '@/mock/articles'

interface ArticlesState {
  // 文章数据
  articles: NewsArticle[]
  hotArticles: NewsArticle[]
  latestArticles: NewsArticle[]
  currentArticle: NewsArticle | null
  recommendedArticles: NewsArticle[]
  
  // 分类数据
  categories: Category[]
  
  // 搜索相关
  searchResults: NewsArticle[]
  searchKeyword: string
  
  // 加载状态
  loading: boolean
  
  // 分页
  currentPage: number
  pageSize: number
  total: number
}

export const useArticlesStore = defineStore('articles', {
  state: (): ArticlesState => ({
    articles: [],
    hotArticles: [],
    latestArticles: [],
    currentArticle: null,
    recommendedArticles: [],
    categories: [],
    searchResults: [],
    searchKeyword: '',
    loading: false,
    currentPage: 1,
    pageSize: 12,
    total: 0
  }),

  getters: {
    // 获取分页后的文章列表
    paginatedArticles: (state) => {
      const start = (state.currentPage - 1) * state.pageSize
      const end = start + state.pageSize
      return state.articles.slice(start, end)
    },
    
    // 检查是否有更多文章
    hasMoreArticles: (state) => {
      return state.currentPage * state.pageSize < state.total
    },
    
    // 获取分类统计
    categoryStats: (state) => {
      return state.categories.map(category => ({
        ...category,
        count: state.articles.filter(
          article => article.category.toLowerCase() === category.id
        ).length
      }))
    }
  },

  actions: {
    // 初始化数据
    async initializeData() {
      this.loading = true
      try {
        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500))
        
        this.articles = mockArticles
        this.categories = mockCategories
        this.hotArticles = getHotArticles(6)
        this.latestArticles = getLatestArticles(10)
        this.total = mockArticles.length
        
        console.log('数据初始化完成:', {
          articles: this.articles.length,
          categories: this.categories.length,
          hotArticles: this.hotArticles.length
        })
      } catch (error) {
        console.error('数据初始化失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 获取文章列表
    async fetchArticles(params: Partial<SearchParams> = {}) {
      this.loading = true
      try {
        await new Promise(resolve => setTimeout(resolve, 300))
        
        if (params.category) {
          this.articles = getArticlesByCategory(params.category, 50)
        } else {
          this.articles = mockArticles
        }
        
        this.total = this.articles.length
        this.currentPage = params.page || 1
      } catch (error) {
        console.error('获取文章失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 根据ID获取文章详情
    async fetchArticleById(id: string) {
      this.loading = true
      try {
        await new Promise(resolve => setTimeout(resolve, 200))
        
        const article = getArticleById(id)
        if (article) {
          this.currentArticle = article
          // 获取推荐文章
          this.recommendedArticles = getRecommendedArticles(article, 5)
          // 增加阅读量（模拟）
          article.readCount += 1
        } else {
          this.currentArticle = null
          this.recommendedArticles = []
        }
      } catch (error) {
        console.error('获取文章详情失败:', error)
        this.currentArticle = null
      } finally {
        this.loading = false
      }
    },

    // 搜索文章
    async searchArticles(keyword: string) {
      if (!keyword.trim()) {
        this.searchResults = []
        this.searchKeyword = ''
        return
      }

      this.loading = true
      this.searchKeyword = keyword
      
      try {
        await new Promise(resolve => setTimeout(resolve, 300))
        this.searchResults = searchArticles(keyword, 30)
      } catch (error) {
        console.error('搜索失败:', error)
        this.searchResults = []
      } finally {
        this.loading = false
      }
    },

    // 点赞文章
    async likeArticle(articleId: string) {
      const article = this.articles.find(a => a.id === articleId) ||
                     this.currentArticle
      
      if (article) {
        article.likeCount += 1
        
        // 如果是当前文章，同步更新
        if (this.currentArticle && this.currentArticle.id === articleId) {
          this.currentArticle.likeCount = article.likeCount
        }
      }
    },

    // 清空搜索结果
    clearSearch() {
      this.searchResults = []
      this.searchKeyword = ''
    },

    // 重置状态
    resetState() {
      this.articles = []
      this.hotArticles = []
      this.latestArticles = []
      this.currentArticle = null
      this.recommendedArticles = []
      this.searchResults = []
      this.searchKeyword = ''
      this.currentPage = 1
      this.total = 0
    },

    // 设置当前页
    setCurrentPage(page: number) {
      this.currentPage = page
    },

    // 加载更多文章（无限滚动）
    async loadMoreArticles() {
      if (!this.hasMoreArticles || this.loading) {
        return
      }

      this.loading = true
      try {
        await new Promise(resolve => setTimeout(resolve, 500))
        
        const nextPage = this.currentPage + 1
        const start = (nextPage - 1) * this.pageSize
        const end = start + this.pageSize
        const moreArticles = mockArticles.slice(start, end)
        
        this.articles.push(...moreArticles)
        this.currentPage = nextPage
      } catch (error) {
        console.error('加载更多文章失败:', error)
      } finally {
        this.loading = false
      }
    }
  }
})